package com.sprometheus.send.feishu;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.sprometheus.core.constants.Scene;
import com.sprometheus.core.constants.SendChannel;
import com.sprometheus.core.pojo.GlobalExceptionBO;
import com.sprometheus.send.SendMessage;
import net.jodah.expiringmap.ExpirationPolicy;
import net.jodah.expiringmap.ExpiringMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;


@Service(SendChannel.FEISHU)
public class FeishuSendMessage implements SendMessage {
    public static final String SYS_ERROR_FEISHU = "sys:error:feishu:monitorType:%s:title:%s:";
    public static final String statusMessage = "StatusMessage";
    public static final String statusCode = "StatusCode";
    public static final String success = "success";
    public static final String textField = "text";
    public static final String msgType = "msg_type";
    public static final String contentField = "content";
    public static final int duration = 2;
    public static final int maxSize = 4096;
    private static final Logger logger = LoggerFactory.getLogger(FeishuSendMessage.class);
    private static final ExpiringMap<String, String> CACHE_MAP = ExpiringMap.builder()
            .maxSize(maxSize)
            .expiration(duration, TimeUnit.MINUTES)
            .expirationPolicy(ExpirationPolicy.ACCESSED)
            .variableExpiration()
            .build();

    @Override
    public boolean send(GlobalExceptionBO message) {
        try {
            logger.info("traceId:{}", message.getTraceId());
            String title = message.getTitle();
            String monitorType = message.getMonitorType();
            String exceptionMessage = message.getExceptionMessage();
            String content = monitorType + title + exceptionMessage;
            String md5 = MD5.create().digestHex16(content);
            String key = String.format(SYS_ERROR_FEISHU, monitorType, title) + md5;
            if (CACHE_MAP.containsKey(key)) {
                logger.error("飞书群通知重复,不予推送");
                return true;
            }
            logger.info("飞书群异常通知:{}", message.getExceptionMessage());
            String fsMsg;
            if (Scene.ORIGIN_MSG.toString().equalsIgnoreCase(message.getScene())) {
                fsMsg = message.toString();
            } else {
                JSONObject params = new JSONObject();
                JSONObject text = new JSONObject();
                text.set(textField, message.toString());
                params.set(msgType, textField);
                params.set(contentField, text);
                fsMsg = params.toString();
            }
            String fsWebhook = message.getGroupUrl();
            String result = HttpUtil.post(fsWebhook, fsMsg);
            logger.info("飞书通知响应结果：{}", result);
            if (StrUtil.isBlank(result)) return false;
            JSONObject obj = JSONUtil.parseObj(result);
            if (!success.equalsIgnoreCase(obj.getStr(statusMessage)) || obj.getInt(statusCode) != 0) {
                logger.error("飞书[webhook]响应异常,{}", result);
                return false;
            }
        } catch (Exception e) {
            logger.error("飞书群通知异常");
            return false;
        }
        return true;
    }

}
